package com.ktjiaoyu.crm.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.service.RightService;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    private RightService rightService;

    /**
     * 开启 Shiro 注解(如@RequiresRoles,@RequiresPermissions),
     * 需借助 SpringAOP 扫描使用 Shiro 注解的类,并在必要时进行安全逻辑验证
     * 配置以下两个 bean(DefaultAdvisorAutoProxyCreator 和
     AuthorizationAttributeSourceAdvisor)
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启 aop 注解支持
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean   //装配自定义Realm
    public MyShiroRealm myShiroRealm(){

        return new MyShiroRealm();
    }

    @Bean   //装配安全管理器
    public SecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //注入自定义Realm
        securityManager.setRealm(myShiroRealm());

        return securityManager;
    }

    @Bean //装配过滤器
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //注入SecurityManager
        shiroFilterFactoryBean.setSecurityManager(manager);
        //权限验证：使用fileter控制资源访问
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setSuccessUrl("/main");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        //用LinkedHashMap添加拦截的uri,其中authc指定需要认证的uri，anon指定排除认证的uri
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

        //anon:所有url都都可以匿名访问(无须登录即可访问);
        //authc:需要认证才能进行访问(必须登录才能访问);
        //user:配置记住我或认证通过可以访问；
        //配置可以匿名访问的资源：静态资源
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/images/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/localcss/**","anon");
        filterChainDefinitionMap.put("/localjs/**","anon");
        filterChainDefinitionMap.put("/login","anon");
        filterChainDefinitionMap.put("/main","anon");

        //中间的配置表示：哪些资源需要经过权限校验才能访问
        //静态授权：包括全部需要特定权限才能访问的资源(URL)
        /*filterChainDefinitionMap.put("/user/list","perms[list]");
        filterChainDefinitionMap.put("/user/add","roles[管理员,客户经理]");
        //filterChainDefinitionMap.put("/user/add","perms[user:add]");
        filterChainDefinitionMap.put("/user/edit","perms[user:update]");
        filterChainDefinitionMap.put("/user/del","perms[user:delete]");*/

        //动态授权：从数据库查询所有权限列表
        /*List<Right> rightList = rightService.findAllRights();
        //遍历权限列表
        for (Right right : rightList){
            //此处判断URL不为空是因为父权限URL不需要跳转页面，所以会出现空的情况
            //需要排除父权限URL
            if(right.getRightUrl()!=null && !right.getRightUrl().trim().equals("")){
                filterChainDefinitionMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }*/
        //配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**","authc"); //必须放在过滤器链的最后面

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {//thymeleaf 页面上使用 shiro 标签
        return new ShiroDialect();
    }

}
